package com.frxuexi.park

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.frxuexi.lib_base.entity.ParkBean
import com.frxuexi.lib_base.entity.ParkBeanItem
import com.frxuexi.lib_base.entity.Res
import com.frxuexi.lib_base.http.ApiService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext
import java.lang.Exception

class ParkDataSource(val apiService: ApiService,val para:String,val type:String):PagingSource<Int,ParkBeanItem>() {
    override fun getRefreshKey(state: PagingState<Int, ParkBeanItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ParkBeanItem> {
        return withContext(Dispatchers.IO){
            try {
                val page=params.key?:0
                var res:Res<ParkBean>?=null
                if(type=="类型") {
                    res = apiService.getParksByType(para).first()
                }else if(type=="状态"){
                    res=apiService.getParksByStatus(para).first()
                }else if(type=="区域"){
                    res=apiService.getParksByArea(para.toInt()).first()
                }
                if(res?.code==200){
                    LoadResult.Page(res.data.sortedByDescending { it.id },null,null)
                }else{
                    LoadResult.Error(Exception(res?.message))
                }

            }catch (e:Exception){
                LoadResult.Error(Exception(e))
            }

        }
    }
}